package com.ckzp.plugins.sms;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.ckzp.core.Results;
import com.ckzp.core.json.Jmode;


import com.aliyuncs.dysmsapi.model.v20170525.*;
import com.jfinal.kit.LogKit;

/**
 * need
 * daliyun-java-sdk-dysmsapi-2.2.1.jar
 * aliyun-java-sdk-core-4.1.0.jar
 * gson.jar
 * Created by 51594 on 2022/8/18.
 */
public class AliyunSmsUtil {

    public static AliyunSmsUtil n() {
        return new AliyunSmsUtil();
    }

    public static String accessKeyId = "";
    public static String accessSecret = "";
    public static String templateCode = "";
    //public static String signName = "小移同学";
    // public static String signName = "移唯校园";

    /**
     * @param phone 电话号码
     * @param code  自定义的验证码
     * @return void
     * @Title: sendSMS
     * @Description: 阿里云发送短信
     */
    public static Results sendSMS(String phone, int code, String signName) {

        Results results = Results.n(9, "发送失败");
        try {
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
            IAcsClient client = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(phone);
            request.setEndpoint("dysmsapi.aliyuncs.com");
            request.setSignName(signName);
            request.setTemplateCode(templateCode);
            request.setTemplateParam(Jmode.n().set("code", code).toJson());
            try {
                SendSmsResponse response = client.getAcsResponse(request);
                if ("OK".equals(response.getCode())) {
                    results.setCode(0).setMsg("发送成功");
                }
            } catch (ServerException e) {
                LogKit.error(e.getMessage());
                results.setMsg(e.getErrMsg()).setMessage(e.getMessage());
            } catch (ClientException e) {
                LogKit.error(e.getMessage());
                results.setMsg(e.getErrMsg()).setMessage(e.getErrCode() + e.getRequestId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            results.setMsg(e.getMessage()).setMessage(e.getMessage());
        }
        return results;
    }

    public static void main(String[] arg) {
        AliyunSmsUtil.sendSMS("13980702090", 3456, "移唯校园");
    }
}
